<?php

namespace app\model;

use  DOMDocument;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Cell;

class Util
{


    public static function decodeUnicode($str)
    {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return iconv("UCS-2BE","UTF-8",pack("H*", $matches[1]));'), $str);
    }


    static function themeUrl($themeid)
    {
        global $_G;
        if ($themeid <= 0) {
            return false;
        }
        $url = $_G['siteroot'] . 'app/index.php?i=' . $_G['mpid'] . '&c=entry&themeid=' . $themeid . '&do=index&m=' . MODULE_NAME;
        return $url;
    }

    static function themeUrlnew($do, $themeid, $softkey)
    {
        global $_G;
        if ($themeid <= 0) {
            return false;
        }
        $url = $_G['url_scheme'] . DOMAIN0 . '/' . MODULE_NAME . '/' . $_G['mpid'] . '/' . $themeid . '/0/' . $do . '.aspx?soft=' . $softkey;
        return $url;
    }

    static function lock_url($txt, $key = 'XYZabc')
    {
        $txt = $txt . $key;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }
        return urlencode(base64_encode($ch . $tmp));
    }

    static function unlock_url($txt, $key = 'XYZabc')
    {
        $txt = base64_decode(urldecode($txt));
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) $j += 64;
            $tmp .= $chars[$j];
        }
        return trim(base64_decode($tmp), $key);
    }


    static function importExcel($excefile)
    {
        global $_G;
        $path = ATTACHMENT_ROOT . 'excel';
        if (!is_dir($path)) {
            mkdir($path, '0777');
        }

        $filename = $_FILES[$excefile]['name'];
        $tmpname = $_FILES[$excefile]['tmp_name'];

        if (empty($tmpname)) {
            return_msg('请选择要上传的Excel文件!', '', 'error');
        }

        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if (($ext != 'xlsx') && ($ext != 'xls')) {
            return_msg('请上传 xls 或 xlsx 格式的Excel文件!', '', 'error');
        }

        $file = time() . $_G['mpid'] . '.' . $ext;
        $uploadfile = $path . $file;
        $result = move_uploaded_file($tmpname, $uploadfile);

        if (!$result) {
            return_msg('上传Excel 文件失败, 请重新上传!', '', 'error');
        }

        $reader = PHPExcel_IOFactory::createReader($ext == 'xls' ? 'Excel5' : 'Excel2007');
        $excel = $reader->load($uploadfile);
        $sheet = $excel->getActiveSheet();
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $highestColumnCount = PHPExcel_Cell::columnIndexFromString($highestColumn);
        $values = array();
        $row = 2;

        while ($row <= $highestRow) {
            $rowValue = array();
            $col = 0;

            while ($col < $highestColumnCount) {
                $rowValue[] = $sheet->getCellByColumnAndRow($col, $row)->getValue();
                ++$col;
            }

            $values[] = $rowValue;
            ++$row;
        }

        return $values;
    }


    static function sendAttendNotice($message, $system)
    {
        global $_G;
        $data = array(
            'touser' => $message['openid'],
            'template_id' => $system['attendok'],
            'url' => $message['url'],
            'topcolor' => '#FF0000',
        );
        $data['data'] = array(
            'first' => array(
                'value' => $message['first'],
                'color' => '#173177',
            ),
            'keyword1' => array(
                'value' => $message['keyword1'],
                'color' => '#173177',
            ),
            'keyword2' => array(
                'value' => $message['keyword2'],
                'color' => '#173177',
            ),
            'keyword3' => array(
                'value' => $message['keyword3'],
                'color' => '#173177',
            ),
            'remark' => array(
                'value' => $message['remark'],
                'color' => '#173177',
            ),
        );
        return self::sendMBXX($system, $data);
    }


    static function sendNeworderInfo($system, $theme, $config, $record, $themeid)
    {
        global $_G;
        $worker = Worker::getThemeWorkerByUid($record['workerid'], $themeid, 1);
        if (empty($worker['qruserid']) && $system['tixing'] == 1) {
            yxlog($record, '定单提醒失败');
            return;
        }
        // var_dump($worker);
        if ($record['type'] == 9) {
            $orderType = '单买';
        } elseif ($record['type'] == 1) {
            $orderType = '团员';
        } elseif ($record['type'] == 8) {
            $orderType = '补款';
        } elseif (intval($config['maxcountall']) > 1) {
            $orderType = '团长';
        } else {
            $orderType = '已支付';
        }
        $todaytime = strtotime(date("Y-m-d 00:00:00"));
        $paycounttoday = (int)db_fetchcolumn('SELECT COUNT(*) FROM ' . tablename(t_record) . "
                    WHERE status > 0 and workerid = '{$record['workerid']}' and addtime>'{$todaytime}' and themeid = '{$themeid}' ");
        $paycount = (int)db_fetchcolumn('SELECT COUNT(*) FROM ' . tablename(t_record) . "
                    WHERE status > 0 and workerid = '{$record['workerid']}' and themeid = '{$themeid}' ");
        $message = array(
            'server' => DOMAIN0,
            'softname' => MODULE_NAME,
            'uniacid' => $_G['mpid'],
            'themeid' => $themeid,
            'qruserid' => $worker['qruserid'],
            "url" => Util::themeUrlnew('w_order', $themeid, $theme['softkey']),
            "openid" => $worker['openid'],
//            "paycounttoday"     =>$paycounttoday,
//            "paycount"     =>$paycount,
//            "paytime"  => date('Y-m-d H:i:s'),
//            "orderType"  => $orderType,
//            "username"  => $record['username'] ,
//            "nickname"  => $record['nickname'] ,
//            "fee"  => $record['fee'] ,
            "first" => '截止' . date('d日H:i分') . ', 您今日成交【 ' . $paycounttoday . ' 】单, 总计 ' . $paycount . ' 单',
            "tradeDateTime" => date('Y-m-d H:i:s'),
            "orderType" => $orderType,
            "customerInfo" => $record['username'],
            "orderItemName" => $record['fee'],
            "orderItemData" => $record['mobile'],
            "remark" => $record['nickname'],
        );
        yxlog($message, '定单提醒');
        // var_dump($message);
        if ($system['tixing'] == 1) {
            if (!empty($worker['qruserid'])) {
                $rec = Poster::ServerQR($system, 'send', $message);
            }
        } else {
            $rec = Util::sendNeworder($message, $system);
        }
        return $rec;
    }

    static function sendNeworder($message, $system)
    {
        global $_G;
        $message['url'] = str_replace('w_order', 'x_order', $message['url']);
        $data = array(
            'touser' => $message['openid'],
            'template_id' => $system['neworder'],
            'url' => $message['url'],
            'page' => 'index',
        );
        $tixing = explode('您', $message['first']);
        $data['data'] = array(
            'thing4' => array(
                'value' => $tixing[1],
            ),
            'thing3' => array(
                'value' => $message['orderItemName'],
            ),
            'thing9' => array(
                'value' => $message['customerInfo'] . "【" . $message['orderType'] . "】",
            ),
            'phone_number10' => array(
                'value' => $message['orderItemData'],
            ),
            'time6' => array(
                'value' => $message['tradeDateTime'],
            ),
        );
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
        return PostByAccessToken($system, $url, $data, true);
//        return self::sendMBXX($system,$data);
    }

    static function sendNeworder_old($message, $system)
    {
        global $_G;
        $data = array(
            'touser' => $message['openid'],
            'template_id' => $system['neworder'],
            'url' => $message['url'],
            'topcolor' => '#FF0000',
        );
        $data['data'] = array(
            'first' => array(
                'value' => $message['first'],
                'color' => '#173177',
            ),
            'tradeDateTime' => array(
                'value' => $message['tradeDateTime'],
                'color' => '#173177',
            ),
            'orderType' => array(
                'value' => $message['orderType'],
                'color' => '#173177',
            ),
            'customerInfo' => array(
                'value' => $message['customerInfo'],
                'color' => '#173177',
            ),
            'orderItemName' => array(
                'value' => $message['orderItemName'],
                'color' => '#000000',
            ),
            'orderItemData' => array(
                'value' => $message['orderItemData'],
                'color' => '#173177',
            ),
            'remark' => array(
                'value' => $message['remark'],
                'color' => '#173177',
            ),
        );
        return self::sendMBXX($system, $data);
    }

    static function showError($text)
    {
        return "<!DOCTYPE html>
                <html>
                    <head>
                        <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
                        <title>抱歉，出错了</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
                    </head>
                    <body>
                    <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><i class='icon80_smile'></i></span><div class='msg_content'><h4>{$text}</h4></div></div></div>
                    </body>
                </html>";
    }


    static function applyrefund($trade, $refundno, $system)
    {
        if ($system['send_mode'] == 1) {
            $ret = Util::profitsharingfinish($trade, $system, $refundno, 4);//自动结算：需退款
            if ($ret['code'] != 0 && $ret['message'] != "-2:分账金额不足" && $ret['message'] != "-2:非分账订单不支持分账") {
                return_msg($ret['message']);
            }
        }
        $ret = array();
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
        libxml_disable_entity_loader(true);

        if ($trade['uniacid'] == $system['wxapp']) {
            $appid = $system['appidxcx'];
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];
            $apiclient_cert = $system['apiclient_certxcx'];
            $apiclient_key = $system['apiclient_keyxcx'];
            $system['mchid_old'] = $system['mchidxcx_old'];
        } else {
            $appid = $system['appid'];
            $machid = $system['mchid'];
            $apikey = $system['apikey'];
            $apiclient_cert = $system['apiclient_cert'];
            $apiclient_key = $system['apiclient_key'];
        }

        $pars = array();
        $pars['appid'] = $appid;
        $pars['mch_id'] = $machid;
        $pars['nonce_str'] = random(32);
        $pars['transaction_id'] = $trade['transaction_id'];
        $pars['out_refund_no'] = $refundno;
        $pars['total_fee'] = $trade['realfee'] * 100;
        $pars['refund_fee'] = $trade['realfee'] * 100;
        $pars['op_user_id'] = $machid;
        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;
        $pars['sign'] = strtoupper(md5($string1));
        $xml = to_xml($pars);
        $extras = array();
        //测试临时修改文件路劲
//        $apiclient_cert = APP_PATH_SYS . 'attachment/cert/7871gtlFKqEHOa_cert.pem';
//        $apiclient_key = APP_PATH_SYS . 'attachment/cert/7871amPFzyu3c1_key.pem';
//        $extras['CURLOPT_CAINFO'] = $system['rootca'];
        $extras['CURLOPT_SSLCERT'] = $apiclient_cert;
        $extras['CURLOPT_SSLKEY'] = $apiclient_key;

        //loadload_func('communication');
//        $procResult = null;
        $resp = yxcurl_xml($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $ret['message'] = "success";
                return $ret;
            } else {
                $error = $resp['err_code_des'];
                $error2 = $resp['return_msg'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error . '*' . $error2;
                if (($ret['message'] == '-2:您的请求参数与订单信息不一致*OK' || $ret['message'] == '-2:商户号与订单不匹配') && $machid != $system['mchid_old'] && !empty($system['mchid_old'])) {
                    $keys = ['appid', 'secret', 'mchid', 'apikey', 'apiclient_cert', 'apiclient_key', 'appidxcx', 'secretxcx', 'mchidxcx', 'apikeyxcx', 'apiclient_certxcx', 'apiclient_keyxcx'];
                    foreach ($keys as $key) {
                        if (!empty($system[$key . '_old'])) {
                            $system[$key] = $system[$key . '_old'];
                        }
                    }
                    return Util::applyrefund($trade, $refundno, $system);
                }
                return $ret;
            }
        }
    }

    //添加分帐接收方
    static function profitsharing_addreceiver($uniacid, $receiver, $system)
    {
        $ret = array();
        $url = 'https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver';
        libxml_disable_entity_loader(true);

        if ($uniacid == $system['wxapp']) {
            $appid = $system['appidxcx'];
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];
        } else {
            $appid = $system['appid'];
            $machid = $system['mchid'];
            $apikey = $system['apikey'];
        }

        $pars = array();
        $pars['mch_id'] = $machid;
        $pars['appid'] = $appid;
        $pars['nonce_str'] = random(32);
        $pars['receiver'] = json_encode($receiver);
        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;
        $pars['sign'] = strtoupper(hash_hmac('sha256', $string1, $apikey));
        $xml = to_xml($pars);

        //loadload_func('communication');
//        $procResult = null;

        $resp = yxcurl_xml($url, $xml);

        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $ret['message'] = "success";
                return $ret;
            } else {
                $error = $resp['err_code_des'];
                $error2 = $resp['return_msg'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error . '*' . $error2;
                return $ret;
            }
        }
    }

    //请求单次分帐
    static function profitsharing($openid, $amount, $ordersn, $desc, $system, $order)
    {
        global $_G;
        $ret = array();
        $amount = $amount * 100;
        $ret['amount'] = $amount;
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharing';
        libxml_disable_entity_loader(true);

        $sql = "SELECT * FROM " . tablename(t_fans) . "
                    WHERE openid = :openid";
        $myfans = db_find($sql, array(":openid" => $openid));

        if ($myfans['uniacid'] == $system['wxapp']) {
            $appid = $system['appidxcx'];
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];
            $apiclient_cert = $system['apiclient_certxcx'];
            $apiclient_key = $system['apiclient_keyxcx'];

        } else {
            $appid = $system['appid'];
            $machid = $system['mchid'];
            $apikey = $system['apikey'];
            $apiclient_cert = $system['apiclient_cert'];
            $apiclient_key = $system['apiclient_key'];
        }

        $pars = array();
        $pars['mch_id'] = $machid;
        $pars['appid'] = $appid;
        $pars['nonce_str'] = random(32);
        $pars['transaction_id'] = $order['transaction_id'];
        $pars['out_order_no'] = $ordersn;

        $receivers[0] = array(
            'type' => 'PERSONAL_OPENID',
            'account' => $openid,
            'amount' => $amount,
            'description' => $desc,
        );
        $pars['receivers'] = json_encode($receivers);

        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;

        $pars['sign'] = strtoupper(hash_hmac('sha256', $string1, $apikey));
        $xml = to_xml($pars);
        $extras = array();
//        $extras['CURLOPT_CAINFO'] = $system['rootca'];
        $extras['CURLOPT_SSLCERT'] = $apiclient_cert;
        $extras['CURLOPT_SSLKEY'] = $apiclient_key;
        //loadload_func('communication');
//        $procResult = null;
        $resp = yxcurl_xml($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $ret['message'] = "success";
                return $ret;
            } else {
                $error = $resp['err_code_des'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error;
                return $ret;
            }
        }

    }


    //请求多次分帐
    static function multiprofitsharing($openid, $amount, $ordersn, $desc, $system, $order)
    {
        global $_G;
        $ret = array();
        $amount = $amount * 100;
        $ret['amount'] = $amount;
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/multiprofitsharing';
        libxml_disable_entity_loader(true);

        $sql = "SELECT * FROM " . tablename(t_fans) . "
                    WHERE openid = :openid";
        $myfans = db_find($sql, array(":openid" => $openid));

        if ($myfans['uniacid'] == $system['wxapp']) {
            $appid = $system['appidxcx'];
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];
            $apiclient_cert = $system['apiclient_certxcx'];
            $apiclient_key = $system['apiclient_keyxcx'];

        } else {
            $appid = $system['appid'];
            $machid = $system['mchid'];
            $apikey = $system['apikey'];
            $apiclient_cert = $system['apiclient_cert'];
            $apiclient_key = $system['apiclient_key'];
        }

        $pars = array();
        $pars['mch_id'] = $machid;
        $pars['appid'] = $appid;
        $pars['nonce_str'] = random(32);
        $pars['transaction_id'] = $order['transaction_id'];
        $pars['out_order_no'] = $ordersn;

        $receivers[0] = array(
            'type' => 'PERSONAL_OPENID',
            'account' => $openid,
            'amount' => $amount,
            'description' => $desc,
        );
        $pars['receivers'] = json_encode($receivers);

        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;

        $pars['sign'] = strtoupper(hash_hmac('sha256', $string1, $apikey));
        $xml = to_xml($pars);
        $extras = array();
//        $extras['CURLOPT_CAINFO'] = $system['rootca'];
        $extras['CURLOPT_SSLCERT'] = $apiclient_cert;
        $extras['CURLOPT_SSLKEY'] = $apiclient_key;
        //loadload_func('communication');
//        $procResult = null;
        $resp = yxcurl_xml($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $ret['message'] = "success";
                return $ret;
            } else {
                $error = $resp['err_code_des'];
                $err_code = $resp['err_code'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error;
                $ret['err_code'] = $err_code;
                return $ret;
            }
        }

    }

    //完结分账
    static function profitsharingfinish($trade, $system, $refundno, $mode)
    {
        //1 手工结算
        //2 自动结算：所属定单完成分帐
        //3 自动结算：达到分帐上限
        //4 自动结算：需退款
        //5 自动结算：活动结束
        global $_G;
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharingfinish';
        libxml_disable_entity_loader(true);

        if ($trade['uniacid'] == $system['wxapp']) {
            $appid = $system['appidxcx'];
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];
            $apiclient_cert = $system['apiclient_certxcx'];
            $apiclient_key = $system['apiclient_keyxcx'];

        } else {
            $appid = $system['appid'];
            $machid = $system['mchid'];
            $apikey = $system['apikey'];
            $apiclient_cert = $system['apiclient_cert'];
            $apiclient_key = $system['apiclient_key'];
        }

        $pars = array();
        $pars['mch_id'] = $machid;
        $pars['appid'] = $appid;
        $pars['nonce_str'] = random(32);
        $pars['transaction_id'] = $trade['transaction_id'];
        $pars['out_order_no'] = $refundno;
        $pars['description'] = '分账已完成';

        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;

        $pars['sign'] = strtoupper(hash_hmac('sha256', $string1, $apikey));
        $xml = to_xml($pars);
        $extras = array();
//        $extras['CURLOPT_CAINFO'] = $system['rootca'];
        $extras['CURLOPT_SSLCERT'] = $apiclient_cert;
        $extras['CURLOPT_SSLKEY'] = $apiclient_key;
        //loadload_func('communication');
//        $procResult = null;
        $resp = yxcurl_xml($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $ret['message'] = "success";
            } else {
                $error = $resp['err_code_des'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error;
            }
            if ($ret['code'] == 0 || $ret['message'] == "-2:分账金额不足" || $ret['message'] == "-2:非分账订单不支持分账") {
                db_update(t_order, array('profitsharingfinish' => $mode), array('id' => $trade['id']));
            }
            return $ret;
        }

    }

    //查询分账结果
    static function profitsharingquery($trade, $system)
    {
        $order = db_find("SELECT * FROM " . tablename(t_order) . " WHERE ordersn ='{$trade['ordersn']}'");

        $url = 'https://api.mch.weixin.qq.com/pay/profitsharingquery';
        libxml_disable_entity_loader(true);

        if ($trade['uniacid'] == $system['wxapp']) {
            $appid = $system['appidxcx'];
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];
            $apiclient_cert = $system['apiclient_certxcx'];
            $apiclient_key = $system['apiclient_keyxcx'];

        } else {
            $appid = $system['appid'];
            $machid = $system['mchid'];
            $apikey = $system['apikey'];
            $apiclient_cert = $system['apiclient_cert'];
            $apiclient_key = $system['apiclient_key'];
        }

        $pars = array();
        $pars['mch_id'] = $machid;
        $pars['nonce_str'] = random(32);
        $pars['transaction_id'] = $order['tid'];
        $pars['out_order_no'] = $order['ordersn'];

        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;

        $pars['sign'] = strtoupper(hash_hmac('sha256', $string1, $apikey));
        $xml = to_xml($pars);
        $extras = array();
//        $extras['CURLOPT_CAINFO'] = $system['rootca'];
        $extras['CURLOPT_SSLCERT'] = $apiclient_cert;
        $extras['CURLOPT_SSLKEY'] = $apiclient_key;
        //loadload_func('communication');
//        $procResult = null;
        $resp = yxcurl_xml($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $status = $resp['status'];
                if ($status == 'FINISHED') {
                    $receivers = $resp['receivers'];
                    $receivers = json_decode($receivers, true);
                    if ($receivers[0]['result'] == 'SUCCESS') {
                        $comm_status = $trade['type'] == '99' ? 99 : 1;
                        db_query("UPDATE " . tablename(t_comm) . " SET status = '{$comm_status}',msg='自动发放' WHERE id='{$trade['id']}'");
                        $ret['message'] = '红包已到账';
                    } else {
                        yxlog($receivers, '分账失败');
                        $ret['code'] = -2;
                        $ret['message'] = $receivers[0]['fail_reason'];
                        if ($receivers[0]['fail_reason'] == 'RECEIVER_HIGH_RISK') {
                            $ret['message'] = '未到账：此微信有风险';
                        }
                        db_query("UPDATE " . tablename(t_comm) . " SET status = 0,msg='-2:{$ret['message']}' WHERE id='{$trade['id']}'");
                    }
                } elseif ($status == 'PROCESSING') {
                    $ret['message'] = '红包处理中';
                } else {
                    $ret['message'] = $status;
                }
                return $ret;
            } else {
                $error = $resp['return_msg'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error;
                return $ret;
            }
        }

    }

    //查询订单待分账金额
    static function profitsharingorderamountquery($order, $system)
    {
        global $_G;
        $url = 'https://api.mch.weixin.qq.com/pay/profitsharingorderamountquery';
        libxml_disable_entity_loader(true);
        $transaction_id = $order['transaction_id'];

        if ($order['uniacid'] == $system['wxapp']) {
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];

        } else {
            $machid = $system['mchid'];
            $apikey = $system['apikey'];
        }

        $pars = array();
        $pars['mch_id'] = $machid;
        $pars['nonce_str'] = random(32);
        $pars['transaction_id'] = $transaction_id;

        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;

        $pars['sign'] = strtoupper(hash_hmac('sha256', $string1, $apikey));
        $xml = to_xml($pars);

        //loadload_func('communication');
        $procResult = null;
        $resp = yxcurl_xml($url, $xml);
        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $ret['message'] = $resp['unsplit_amount'];
                return $ret;
            } else {
                $error = $resp['err_code_des'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error;
                return $ret;
            }
        }

    }

    static function sendPointNotice($message, $system)
    {
        global $_G;
        $data = array(
            'touser' => $message['openid'],
            'template_id' => $system['msgpoint'],
            'url' => $message['url'],
            'topcolor' => '#FF0000',
        );
        $data['data'] = array(
            'first' => array(
                'value' => $message['first'],
                'color' => '#173177',
            ),
            'keyword1' => array(
                'value' => $message['keyword1'],
                'color' => '#173177',
            ),
            'keyword2' => array(
                'value' => $message['keyword2'],
                'color' => '#173177',
            ),
            'keyword3' => array(
                'value' => $message['keyword3'],
                'color' => '#173177',
            ),
            'keyword4' => array(
                'value' => $message['keyword4'],
                'color' => '#173177',
            ),
            'keyword5' => array(
                'value' => $message['keyword5'],
                'color' => '#173177',
            ),

            'remark' => array(
                'value' => $message['remark'],
                'color' => '#173177',
            ),
        );
        return self::sendMBXX($system, $data);
    }


    static function sendHeXiaoNotice($message, $system)
    {
        global $_G;
        $data = array(
            'touser' => $message['openid'],
            'template_id' => $system['msgverify'],
            'url' => $message['url'],
            'topcolor' => '#FF0000',
        );
        $data['data'] = array(
            'first' => array(
                'value' => $message['first'],
                'color' => '#173177',
            ),
            'keyword1' => array(
                'value' => $message['keyword1'],
                'color' => '#173177',
            ),
            'keyword2' => array(
                'value' => $message['keyword2'],
                'color' => '#173177',
            ),
            'keyword3' => array(
                'value' => $message['keyword3'],
                'color' => '#173177',
            ),
            'remark' => array(
                'value' => $message['remark'],
                'color' => '#173177',
            ),
        );
        return self::sendMBXX($system, $data);
    }

    static function sendBuyNotice($message, $system)
    {
        global $_G;
        $data = array(
            'touser' => $message['openid'],
            'template_id' => $system['msgbuy'],
            'url' => $message['url'],
            'topcolor' => '#FF0000',
        );
        $data['data'] = array(
            'name' => array(
                'value' => $message['name'],
                'color' => '#173177',
            ),
            'remark' => array(
                'value' => $message['remark'],
                'color' => '#173177',
            ),
        );
        return self::sendMBXX($system, $data);
    }


    static function sendCommNotice($message, $system)
    {
        global $_G;
        $data = array(
            'touser' => $message['openid'],
            'template_id' => $system['msgcomm'],
            'url' => $message['url'],
            'topcolor' => '#FF0000',
        );
        $data['data'] = array(
            'first' => array(
                'value' => $message['first'],
                'color' => '#173177',
            ),
            'keyword1' => array(
                'value' => $message['keyword1'],
                'color' => '#173177',
            ),
            'keyword2' => array(
                'value' => $message['keyword2'],
                'color' => '#173177',
            ),
            'keyword3' => array(
                'value' => $message['keyword3'],
                'color' => '#173177',
            ),
            'keyword4' => array(
                'value' => $message['keyword4'],
                'color' => '#173177',
            ),
            'keyword5' => array(
                'value' => $message['keyword5'],
                'color' => '#173177',
            ),

            'remark' => array(
                'value' => $message['remark'],
                'color' => '#173177',
            ),
        );
        return self::sendMBXX($system, $data);
    }


    //拼团成功通知 【门店名称 成团人数 成团时间 温馨提示】
    static function send_mb_group_success($system, $config, $theme, $record)
    {
        $template_id = $system['mb_group_success'];
        if (empty($template_id) || empty($config['mbxx_mode'])) {
            return array('error' => 1, 'data' => array('msg' => '参数错误'));
        }
        $Tuanlist = Record::getAllListByPid($record['pid']);
        $message = array(
            'thing1' => array(
                'value' => mb_substr($theme['jubf'], 0, 20, 'utf-8'),
            ),
            'thing2' => array(
                'value' => count($Tuanlist),
            ),
            'time3' => array(
                'value' => date('Y-m-d H:i:s'),
            ),
            'thing4' => array(
                'value' => '恭喜您，拼团成功啦！点击查看详情',
            ),
        );
        foreach ($Tuanlist as $index => $row) {
            Util::sendMBXCX($system, $theme, $row['openid'], $template_id, $message);
        }
    }

    //助力成功通知 【助力人数 成功时间 温馨提示】
    static function send_mb_help_success($system, $config, $theme, $uid)
    {
        $template_id = $system['mb_help_success'];
        $fans = Fans::getById($uid, $theme['id']);
        if (empty($template_id) || empty($config['mbxx_mode']) || empty($fans)) {
            return array('error' => 1, 'data' => array('msg' => '参数错误'));
        }

        $message = array(
            'thing9' => array(
                'value' => mb_substr($theme['title'], 0, 20, 'utf-8'),
            ),
            'number1' => array(
                'value' => $fans['friendnum'],
            ),
            'time3' => array(
                'value' => date('Y-m-d H:i:s'),
            ),
            'thing4' => array(
                'value' => '恭喜您，助力成功啦！点击查看详情',
            ),
        );
        Util::sendMBXCX($system, $theme, $fans['openid'], $template_id, $message);
    }

    static function sendMBXCX($system, $theme, $openid, $template_id, $message)
    {
        if (empty($openid)) {
            return array('error' => 1, 'msg' => '参数错误');
        }
        $page = '/pages/index/index?softname=' . MODULE_NAME . '&themeid=' . $theme['id'] . '&softkey=' . $theme['softkey'];
        $data = array(
            'touser' => $openid,
            'template_id' => $template_id,
            'page' => $page,
            'data' => $message,
        );

        $access_token = getAccessToken($system);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
        libxml_disable_entity_loader(true);
        $response = yxcurl($url, json_encode($data));
        $response = @json_decode($response['content'], true);

        if ($response['errcode'] == '0') {
            $result = Ad::usedMBXX($theme['id'], $data);
            if ($result['error'] == 1) {
                return $result;
            }
            $logdata = array(
                'themeid' => $theme['id'],
                'uid' => $result['uid'],
                'template_id' => $template_id,
                'message' => json_encode($message),
                'sendtime' => TIMESTAMP,
            );
            $insertid = db_insert(t_mbxxlog, $logdata);
            return array('error' => 0, 'msg' => '已发送');
        } else {
            return array('error' => 1, 'msg' => $response['errmsg']);
        }
    }

    static function sendMBXX($system, $data)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . getAccessToken($system, true);
        libxml_disable_entity_loader(true);
        return yxcurl($url, json_encode($data));
    }

    // static function getToken() {
    //     global $_G;
    //     load ()->classs ( 'weixin.account' );
    //     $id = $_G ['acid'];
    //     if (empty ( $id )) {
    //         $id = $_G ['uniacid'];
    //     }
    //     $accObj = WeixinAccount::create ( $id );
    //     $access_token = $accObj->fetch_token ();
    //     return $access_token;
    // }

//    static function getToken(){
//    global $_G;
//
//    $appid = $_G ['account'] ['key'];
//    $secret = $_G ['account'] ['secret'];
//
//    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
//
//    $ch1 = curl_init();
//    curl_setopt($ch1, CURLOPT_URL, $url);
//    curl_setopt($ch1, CURLOPT_POST, 1);
//    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
//    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
//    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
//    curl_setopt($ch1, CURLOPT_POSTFIELDS, '');
//    $c = curl_exec($ch1);
//    $result = @json_decode($c, true);
//    return $result['access_token'];
//}


    static function getBizType($type)
    {
        if ($type == 'repair') {
            $biz = '维修';
        } elseif ($type == 'recycle') {
            $biz = '回收';
        } elseif ($type == 'secure') {
            $biz = '激活确认';
        } else {
            $biz = '其他';
        }
        return $biz;
    }


    static function getPayType($type)
    {
        if ($type == 'credit') {
            $biz = '余额';
        } elseif ($type == 'wechat') {
            $biz = '微信';
        } elseif ($type == 'delivery') {
            $biz = '货到付款';
        } elseif ($type == 'cash') {
            $biz = '现金';
        } elseif ($type == 'zfb') {
            $biz = '支付宝';
        } else {
            $biz = '其他';
        }
        return $biz;
    }

    static function array2xml($arr, $level = 1)
    {
        $s = $level == 1 ? "<xml>" : '';
        foreach ($arr as $tagname => $value) {
            if (is_numeric($tagname)) {
                $tagname = $value['TagName'];
                unset($value['TagName']);
            }
            if (!is_array($value)) {
                $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";
            } else {
                $s .= "<{$tagname}>" . array2xml($value, $level + 1) . "</{$tagname}>";
            }
        }
        $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
        return $level == 1 ? $s . "</xml>" : $s;
    }


    /**
     * 提现接口
     * @param unknown $openid
     * @param unknown $amount
     * @param unknown $desc
     * @return multitype:number string
     */
    static function transfer($openid, $amount, $ordersn, $desc, $system)
    {
        global $_G;
        $ret = array();
        $amount = $amount * 100;
        $ret['amount'] = $amount;
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        libxml_disable_entity_loader(true);

        $sql = "SELECT * FROM " . tablename(t_fans) . "
                    WHERE openid = :openid";
        $myfans = db_find($sql, array(":openid" => $openid));

        if ($myfans['uniacid'] == $system['wxapp']) {
            $appid = $system['appidxcx'];
            $machid = $system['mchidxcx'];
            $apikey = $system['apikeyxcx'];
            $apiclient_cert = $system['apiclient_certxcx'];
            $apiclient_key = $system['apiclient_keyxcx'];
            if (empty($system['s']['mchid2xcx'])) {
                $machid = $system['mchidxcx'];
                $apikey = $system['apikeyxcx'];
                $apiclient_cert = $system['apiclient_certxcx'];
                $apiclient_key = $system['apiclient_keyxcx'];
            } else {
                $machid = $system['s']['mchid2xcx'];
                $apikey = $system['s']['apikey2xcx'];
                $apiclient_cert = $system['s']['yixuancert2xcx'];
                $apiclient_key = $system['s']['yixuankey2xcx'];
            }
        } else {
            $appid = $system['appid'];
            $apikey = $system['apikey'];
            if (empty($system['s']['mchid2'])) {
                $machid = $system['mchid'];
                $apikey = $system['apikey'];
                $apiclient_cert = $system['apiclient_cert'];
                $apiclient_key = $system['apiclient_key'];
            } else {
                $machid = $system['s']['mchid2'];
                $apikey = $system['s']['apikey2'];
                $apiclient_cert = $system['s']['yixuancert2'];
                $apiclient_key = $system['s']['yixuankey2'];
            }
        }
//        if (MODULE_NAME == 'io32021') {
//            yxlog(['mchid' => $system['s']['mchid2'], 'apikey' => $system['s']['apikey2'], 'apiclient_cert' => $system['s']['yixuancert2'], 'apiclient_key' => $system['s']['yixuankey2']], '发红包');
//            yxlog(['appid' => $appid, 'mchid' => $machid, 'apikey' => $apikey, 'apiclient_cert' => $apiclient_cert, 'apiclient_key' => $apiclient_key], '发红包');
//        }
        //测试临时修改文件路劲
//        $apiclient_cert = APP_PATH_SYS . 'attachment/cert/7871gtlFKqEHOa_cert.pem';
//        $apiclient_key = APP_PATH_SYS . 'attachment/cert/7871amPFzyu3c1_key.pem';

        $pars = array();
        $pars['mch_appid'] = $appid;
        $pars['mchid'] = $machid;
        $pars['nonce_str'] = random(32);
        $pars['partner_trade_no'] = $ordersn;//random(10). date('Ymd') . random(3);
        $pars['openid'] = $openid;
        $pars['check_name'] = "NO_CHECK";
        $pars['amount'] = $amount;
        $pars['desc'] = $desc;
        $pars['spbill_create_ip'] = '192.168.1.1';

        ksort($pars, SORT_STRING);
        $string1 = '';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=" . $apikey;

        $pars['sign'] = strtoupper(md5($string1));
        $xml = to_xml($pars);
        $extras = array();
//        $extras['CURLOPT_CAINFO'] = $system['rootca'];
        $extras['CURLOPT_SSLCERT'] = $apiclient_cert;
        $extras['CURLOPT_SSLKEY'] = $apiclient_key;
        //loadload_func('communication');
//        $procResult = null;
        $resp = yxcurl_xml($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp['message'];
            $ret['code'] = -1;
            $ret['message'] = "-1:" . $procResult;
            return $ret;
        } else {
            $resp = xmlToArray($resp);
            if (empty($resp)) {
                $ret['code'] = -3;
                $ret['message'] = "error response";
                return $ret;
            }
            if ($resp['return_code'] == 'SUCCESS' && $resp['result_code'] == 'SUCCESS') {
                $ret['code'] = 0;
                $ret['message'] = "success";
                return $ret;
            } else {
                $error = $resp['err_code_des'];
                $ret['code'] = -2;
                $ret['message'] = "-2:" . $error;
                return $ret;
            }
        }

    }


    static function appurl($do, $module = MODULE_NAME, $params = array())
    {
        global $_G;
        // $url = $_G['siteroot'] . 'app/index.php?i=' . $_G['mpid'] . '&c=entry&m=' . $module . '&';
        // if (!empty($do)) {
        //     $url .= "do={$do}&";
        // }
        $url = QRURLNEW;
        if (!empty($params)) {
            $queryString = http_build_query($params, '', '&');
            $url .= $queryString;
        }
        return $url;
    }

    static function getOrderCondition()
    {
        global $_G, $_P;
        $condition = " master.uniacid = '{$_G['mpid']}'";
        $condition .= " and master.addtime > '{$_P['createtime']['start']}' and master.addtime <= '{$_P['createtime']['end']}' ";
        if ($_P['themeid'] != 0) {
            $condition .= " and master.themeid = '{$_P['themeid']}'  ";
        }
        if ($_P['paystate'] >= 0) {
            $condition .= " and master.paystate = '{$_P['paystate']}'  ";
        }
        if ($_P['status'] >= 0) {
            $condition .= " and master.status = '{$_P['status']}'  ";
        }
        if (!empty($_P['keyword'])) {
            $condition .= " and (master.username like '%{$_P['keyword']}%' or master.mobile like '%{$_P['keyword']}%' )";
        }
        return $condition;
    }


    static function newOrderNoticeWorker($uniacid, $orderid)
    {
        global $_G, $_P;
        $url = $_G['siteroot'] . 'app/index.php?i=' . $uniacid . '&c=entry&op=notice&orderid=' . $orderid . '&do=api&m=' . MODULE_NAME;
        //loadload_func('communication');
        $orderdata = array(
            "username" => $_P['username'],
            "mobile" => $_P['mobile'],
            "serviceday" => $_P['serviceday'],
            "timerange" => $_P['rangetime'],
        );
        $response = yxcurl($url, $orderdata);
        return true;
    }


    static function readCacheByShopid($shopid, $uniacid = 0)
    {
        $p = array('key' => $shopid);
        if ($uniacid > 0) {
            $p['uniacid'] = $uniacid;
        }
        $settings = db_get(t_config, $p, array('value'));
        if (is_array($settings)) {
            $settings = xunserializer($settings['value']);
        } else {
            $settings = array();
        }
        return $settings;
    }

    static function checkWxappPayByOrderNo($orderno, $system)
    {
        global $_G;
        $url = "https://api.mch.weixin.qq.com/pay/orderquery";
        $random = random(8);
        $post = array(
            'appid' => $system['wxappid'],
            'out_trade_no' => $orderno,
            'nonce_str' => $random,
            'mch_id' => $system['mchid'],
        );
        ksort($post);
        $string = self::ToUrlParams($post);
        $string .= "&key={$system['apikey']}";
        $sign = md5($string);
        $post['sign'] = strtoupper($sign);
        $resp = self::postXmlCurl(self::ToXml($post), $url);
        libxml_disable_entity_loader(true);
        $resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //print_r($resp);
        if ($resp['return_code'] == 'SUCCESS') {
            if ($resp['result_code'] == 'SUCCESS') {
                if ($resp['trade_state'] == 'SUCCESS') {
                    return array('errcode' => 0, 'fee' => $resp['total_fee'] / 100);
                } else {
                    return array('errcode' => 1, 'errmsg' => '未支付:' . $resp['trade_state']);
                }
            } else {
                return array('errcode' => 1, 'errmsg' => '定单不存在' . $resp['err_code']);
            }

        } else {
            return array('errcode' => 1, 'errmsg' => '查询失败:' . $resp['return_msg']);
        }

    }

    static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if ($useCert == true) {
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        }
    }

    static function ToXml($post)
    {
        $xml = "<xml>";
        foreach ($post as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }


    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    static function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 小程序
     * @param unknown $prepay_id
     * @param unknown $orderno
     * @param unknown $orderid
     * @param unknown $system
     * @return multitype:number unknown Ambigous <string> Ambigous <string, unknown, NULL>
     */
    static function getWxAppPayJsParams($prepay_id, $orderno, $orderid, $system)
    {
        global $_G;
        $random = random(8);
        $post = array(
            'appId' => $system['wxappid'],
            'timeStamp' => time(),
            'nonceStr' => $random,
            'package' => "prepay_id=" . $prepay_id,
            'signType' => 'MD5',
        );
        ksort($post);
        $string = self::ToUrlParams($post);
        $string .= "&key={$system['apikey']}";
        $sign = md5($string);
        $post['paySign'] = strtoupper($sign);
        $result = array(
            "errcode" => 0,
            "auth" => 0,
            "timeStamp" => strval($post['timeStamp']),
            "nonceStr" => $post['nonceStr'],
            "package" => $post['package'],
            "signType" => $post['signType'],
            "paySign" => $post['paySign'],
            "orderno" => $orderno,
            "orderid" => $orderid,
        );
        return $result;
    }

    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    static function getRandomStr($len)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }

    /**
     * 获取毫秒数
     *
     * @return number
     */

//    static function getWxAppPrePayId($desc,$fee,$system){
//        global $_G;
//        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//        $random = random(8);
//        $orderno = self::getMillisecond();
//        $trade_type = 'JSAPI';
//        $post = array(
//            'appid'          =>$system['wxappid'],
//            'mch_id'         =>$system['mchid'],
//            'nonce_str'      =>$random,
//            'body'           =>$desc,
//            'out_trade_no'   =>$orderno,
//            'total_fee'      =>$fee*100,
//            'notify_url'     =>$_G['url_scheme'].$_SERVER['HTTP_HOST'].'/payment/wechat/pay.php',
//            'trade_type'     =>$trade_type,
//            'openid'         =>$_G['openid'],
//            'spbill_create_ip'=>$system['ip'],
//        );
//        ksort($post);
//        $string = self::ToUrlParams($post);
//        $string .= "&key={$system['apikey']}";
//        $sign = md5($string);
//        $post['sign'] = strtoupper($sign);
//        $resp = self::postXmlCurl(self::ToXml($post), $url);
//        libxml_disable_entity_loader(true);
//        $resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
//        if ($resp['result_code'] != 'SUCCESS') {
//            return array('errcode'=>1,'errmsg'=>$resp['return_msg']);
//        }else{
//            return array('errcode'=>0,'prepay_id'=>$resp['prepay_id'],'orderno'=>$orderno);
//        }
//    }


    /**
     * 获取定单号
     *
     * @return number
     */
    static function getBillCode()
    {
        list ($t1, $t2) = explode(' ', microtime());
        $basecode = ( float )sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
        $softid = substr(MODULE_NAME, -4);
        return $softid . date("mdHis") . substr($basecode, 2, 5) . mt_rand(10, 99);
    }


    public static function getRndPhone($type = 1)
    {
        $arr = array(
            130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
            144, 147,
            150, 151, 152, 153, 155, 156, 157, 158, 159,
            176, 177, 178,
            180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
        );
        if ($type == 0) {
            $r = $arr[array_rand($arr)] . '' . '****' . mt_rand(1000, 9999);
        } else {
            $r = $arr[array_rand($arr)] . '' . mt_rand(1000, 9999) . '' . mt_rand(1000, 9999);
        }
        return $r;
    }

    public static function zCode($value)
    {
        if (substr($value, 0, 6) == 'YIXUAN') {
            $keys = "YWRlaVwtcZyAjPinseSmxruCvofHOGKBQLINkDFbXpzgThEMUdJq" . substr(MODULE_NAME, -5);
            $value = substr($value, 6);
        } else {
            $keys = "YWRlaVwtcZyAjPinseSmxruCvofHOGKBQLINkDFbXpzgThEMUdJq";
        }
        $kleng = strlen($keys);
        $num = 0;
        $txt = '';
        $arr = [];
        $alen = ceil(strlen($value) / 3);
        for ($i = 1; $i <= $alen; $i++) {
            $cat1 = strpos($keys, substr($value, $num, 1));
            $num++;
            $cat3 = strpos($keys, substr($value, $num, 1));
            $num++;
            $cat2 = strpos($keys, substr($value, $num, 1));
            $num++;
            $arr[$i] = $cat1 * $kleng * $kleng + $cat2 * $kleng + $cat3;
            $txt .= '&#' . $arr[$i] . ';';
        }
        $txt = html_entity_decode($txt, ENT_QUOTES, 'UTF-8');
        return $txt;
    }

    public static function DescCode($value)
    {
        $keys = "YWRlaVwtcZyAjPinseSmxruCvofHOGKBQLINkDFbXpzgThEMUdJq";
        $kleng = strlen($keys);
        $num = 0;
        $txt = '';
        $arr = [];
        $alen = ceil(strlen($value) / 3);
        for ($i = 1; $i <= $alen; $i++) {
            $cat1 = strpos($keys, substr($value, $num, 1));
            $num++;
            $cat3 = strpos($keys, substr($value, $num, 1));
            $num++;
            $cat2 = strpos($keys, substr($value, $num, 1));
            $num++;
            $arr[$i] = $cat1 * $kleng * $kleng + $cat2 * $kleng + $cat3;
            $txt .= '&#' . $arr[$i] . ';';
        }
        $txt = html_entity_decode($txt, ENT_QUOTES, 'UTF-8');
        return $txt;
    }

    //加密
    public static function AscCode($value)
    {
        $keys = "YWRlaVwtcZyAjPinseSmxruCvofHOGKBQLINkDFbXpzgThEMUdJq";
        $kleng = strlen($keys);
        $kstr = str_split($keys);
        $v = "";
        for ($i = 0; $i < strlen($value); $i++) {
            $cat = self::get_bianma(substr($value, $i, 1));
            $cat1 = $cat % $kleng;
            $cat = ($cat - $cat1) / $kleng;
            $cat2 = $cat % $kleng;
            $cat = ($cat - $cat2) / $kleng;
            $cat3 = $cat % $kleng;
            $v .= $kstr[$cat3] . $kstr[$cat1] . $kstr[$cat2];
        }
        $v = $v;
        return $v;
    }

    public static function get_bianma($str)
    {
        $result = array();
        for ($i = 0, $l = mb_strlen($str, "utf-8"); $i < $l; ++$i) {
            $result[] = self::uniord(mb_substr($str, $i, 1, "utf-8"));
        }
        return join(",", $result);
    }

    public static function uniord($str, $from_encoding = false)
    {
        $from_encoding = $from_encoding ? $from_encoding : 'UTF-8';
        if (strlen($str) == 1) {
            return ord($str);
        }
        $str = mb_convert_encoding($str, 'UCS-4BE', $from_encoding);
        $tmp = unpack('N', $str);
        return $tmp[1];
    }

    //格式化违规字
    public static function formatTxtWechat($txt)
    {
        $txt = str_replace('长', '&#38271;', $txt);
        $txt = str_replace('按', '&#x6309;', $txt);
        $txt = str_replace('分', '&#20998;', $txt);
        $txt = str_replace('享', '&#x4EAB;', $txt);
        $txt = str_replace('友', '&#21451;', $txt);
        $txt = str_replace('圈', '&#x5708;', $txt);
        $txt = str_replace('好', '&#x597d;', $txt);
        $txt = str_replace('团', '&#22242;', $txt);
        $txt = str_replace('购', '&#x8D2D;', $txt);
        $txt = str_replace('拼', '&#x62FC;', $txt);
        $txt = str_replace('队', '&#38431;', $txt);
        $txt = str_replace('组', '&#x7EC4;', $txt);
        $txt = str_replace('片', '&#x7247;', $txt);
        return $txt;
    }


    public static function passport_encrypt($txt, $key = 'yixuan', $expiry = 0)
    {
        $txt = urlencode($txt);
        srand((double)microtime() * 1000000);
        $encrypt_key = md5(rand(0, 32000) . microtime());
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
        }
        $result = sprintf('%010d', $expiry ? $expiry + time() : 0) . self::passport_key($tmp, $key);
        $result = urlencode(base64_encode(self::encrypt($result, 'E', $key)));
        $key = md5($result);
        return substr($key, 0, 6) . $result . substr($key, 6, 26);
    }

    public static function passport_decrypt($txt, $key = 'yixuan')
    {
        $md5 = substr($txt, 0, 6) . substr($txt, -26);
        $txt = substr($txt, 6, strlen($txt) - 32);
        if ($md5 != md5($txt)) {
            return;
        }
        $txt = self::encrypt(base64_decode(urldecode($txt)), 'D', $key);

        if (substr($txt, 0, 10) != 0 && substr($txt, 0, 10) - time() < 0) {
            return;
        }
        $txt = self::passport_key(substr($txt, 10), $key);
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $md5 = $txt[$i];
            $tmp .= $txt[++$i] ^ $md5;
        }
        $tmp = urldecode($tmp);
        return $tmp;
    }

    public static function passport_key($txt, $encrypt_key)
    {
        $encrypt_key = md5($encrypt_key);
        $ctr = 0;
        $tmp = '';

        for ($i = 0; $i < strlen($txt); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
        }
        return $tmp;
    }

//函数encrypt($string,$operation,$key)中$string：需要加密解密的字符串；$operation：判断是加密还是解密，E表示加密，D表示解密；$key：密匙。
    public static function encrypt($string, $operation, $key = 'yixuan')
    {
        $key = md5($key);
        $key_length = strlen($key);
        $string = $operation == 'D' ? utf8_decode(base64_decode($string)) : substr(md5($string . $key), 0, 8) . $string;
        $string_length = strlen($string);
        $rndkey = $box = array();
        $result = '';
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($key[$i % $key_length]);
            $box[$i] = $i;
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));

        }
        if ($operation == 'D') {
            if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
                return substr($result, 8);
            } else {
                return '';
            }
        } else {
            return urlencode(str_replace('=', '', base64_encode(utf8_encode($result))));
        }
    }



//非常给力的authcode加密函数,Discuz!经典代码(带详解)
//函数authcode($string, $operation, $key, $expiry)中的$string：字符串，明文或密文；$operation：DECODE表示解密，其它表示加密；$key：密匙；$expiry：密文有效期。
    public static function authcode2($string, $operation = 'DECODE', $key = 'yixuan', $expiry = 0)
    {
        if ($operation == 'ENCODE') {
            $string = urlencode($string);
        }
        if ($operation == 'DECODE') {
            $md5 = substr($string, 0, 16) . substr($string, -16);
            $string = substr($string, 16, strlen($string) - 32);
            if ($md5 != md5($string)) {
                return;
            }
        }

        // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
        $ckey_length = 5;

        // 密匙
        $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

        // 密匙a会参与加解密
        $keya = md5(substr($key, 0, 16));
        // 密匙b会用来做数据完整性验证
        $keyb = md5(substr($key, 16, 16));
        // 密匙c用于变化生成的密文
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
        // 参与运算的密匙
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
        //解密时会通过这个密匙验证数据完整性
        // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
        $string = $operation == 'DECODE' ? utf8_decode(base64_decode(substr($string, $ckey_length))) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 229);
        $rndkey = array();
        // 产生密匙簿
        for ($i = 0; $i <= 229; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
        for ($j = $i = 0; $i < 230; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 230;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        // 核心加解密部分
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 230;
            $j = ($j + $box[$a]) % 230;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            // 从密匙簿得出密匙进行异或，再转成字符
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 230]));
        }
        if ($operation == 'DECODE') {
            // 验证数据有效性，请看未加密明文的格式
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return urldecode(substr($result, 26));
            } else {
                return '';
            }
        } else {
            // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
            // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
            $result = $keyc . str_replace('=', '', base64_encode(utf8_encode($result)));
            $key = md5($result);
            return substr($key, 0, 16) . $result . substr($key, 16, 16);
        }
    }

    /**
     * Desc:检测微信跳转下载
     * User: mf
     * Time: 2023/8/31 14:04
     * @param $html
     * @param $header1
     * @param $header2
     * @param $_G
     * @param $themeid
     */
    public static function WxJump($system, $html, $filename, $themeid, $isend = 1, $allpage = 0)
    {
        global $_G, $_P;
        $header1 = 'Content-type:text/csv';
        $filename = $filename . '-' . date('ymdHis', time());
        $header2 = 'Content-Disposition:attachment; filename=' . $filename . '.csv';
        $page = max(1, intval($_P['ex_page']));
        if (!$allpage) {
            $allpage = $page;
        }

//        if ($page == 1 && $isend == 1) {
//            //判断来自微信浏览器
//            if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
//                $secret_key = self::ExcelInsert($html, $header1, $header2);
////            if (DOMAIN1 == "www.yixuan.net"){
////                $domain = 'http://' . $system['domainhead1'];
////            }else{
////                $domain = $_G['url_scheme']. $system['s']['domain1'];
////            }
//                $res_url =  $_G['url_scheme'] . $_SERVER['HTTP_HOST'] . "/" . MODULE_NAME . "/" . $_G['mpid'] . "/" . $themeid . "/0/excel.aspx?op=show_page&secret_key=" . $secret_key;
//                header("Location: " . $res_url);
//            } else {
//                header("Content-type:text/csv");
//                header($header2);
//                echo $html;
//                exit();
//            }
//        } else {
        if ($page != 1) {//去表头
            $first_line = strpos($html, "\n");
            $html = substr($html, $first_line);
            $get_secret_key = $_P['secret_key'];
            $old_excel = db_getcolumn('excel', array('secret_key' => $get_secret_key, 'software' => MODULE_NAME), 'excel');
            $old_excel = urldecode($old_excel);
            $all_excel = $old_excel . $html;
            $secret_key = self::insertPage($all_excel, $get_secret_key, $page);
        } else {
            $referer_url = $_SERVER['HTTP_REFERER'];
            setcookie('download_excel_referer_url', $referer_url, time() + 180, '/');
            $secret_key = self::ExcelInsert($html, $header1, $header2);
        }
        //$wait_page = self::ExcelWaitPage($page, $allpage);
        // echo $wait_page;
        if (!$isend) {
            $query = $_P;
            unset($query['c']);
            unset($query['a']);
            unset($query['do']);
            $query['ex_page'] = $page + 1;
            $query['secret_key'] = $secret_key;
            $res_url = createWebUrl($_P['do'], $query);
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$res_url';";
            echo "</script>";
            exit;
        } else {
            //  echo '恭喜您，导出成功';
            $res_url = $_G['url_scheme'] . $_SERVER['HTTP_HOST'] . "/" . MODULE_NAME . "/" . $_G['mpid'] . "/" . $themeid . "/0/excel.aspx?op=show_page&secret_key=" . $secret_key;
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
                header("Location: " . $res_url);
            } else {
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$res_url';";
                echo "</script>";
                exit;
            }
        }
        //}
    }

    public static function ExcelWaitPage($page, $allpage)
    {
        $html = "<div style='width:100%;height:100%;background-color:#fcfcfd'>
                          <div   style='position: absolute;left:50%;top:50%;transform: translate(-50%, -50%);'>
                            <div style='text-align:center;font-size:26px'>正在导出</div>
                            <div style=''>
                               <img  src='https://css2020.yixuan.net/2020css/yx2020/images/car-loading.gif' style='display:block;margin:auto'>
                            </div>
                             <div style='text-align:center;font-size:26px'>
                               第<span style='font-size:42px;font-weight:600;color:#15aefb'>{$page}</span>页/共<span style='font-size:42px;font-weight:600;color:#00ada0'>{$allpage}</span>页
                             </div>
                           </div>
                          </div> ";
        return $html;
    }

    /**
     * Desc: excel数据写入库
     * User: mf
     * Time: 2023/8/28 17:14
     * @param $html
     * @param $header1
     * @param $header2
     * @return string
     */
    public static function ExcelInsert($html, $header1, $header2)
    {
        self::ExcelInsertSql();
        $html = urlencode($html);
        $secret_key = rand(1000, 9999) . time();
        $data['excel'] = $html;
        $data['secret_key'] = $secret_key;
        $data['effective_time'] = time() + 600;
        $data['software'] = MODULE_NAME;
        $data['header1'] = $header1;
        $data['header2'] = $header2;
        $data['open_num'] = 0;
        $result = $insertid = db_insert('excel', $data);
        $now_time = time();
        $all_effecttive_time = time() - 600;
        $software = MODULE_NAME;
        $delete_sql = "delete from " . tablename('excel') . " where (effective_time <{$now_time} and software = '{$software}') or effective_time<{$all_effecttive_time}";
        db_query($delete_sql);
        return $secret_key;
    }

    /**
     * Desc:分页excel数据写入库
     * User: mf
     * Time: 2023/8/29 17:20
     * @param $html
     * @param $secret_key
     * @param $page
     * @param $header1
     * @param $header2
     * @return mixed|string
     */
    public static function insertPage($html, $secret_key, $page)
    {
        $effective_time = time() + 600;
        $html = urlencode($html);
        $update_sql = "UPDATE " . tablename('excel') . " SET excel = '{$html}',page =$page,effective_time=$effective_time,open_num = 0  WHERE secret_key = $secret_key";
        $update = db_query($update_sql);
        return $secret_key;
    }

    public static function ExcelInsertSql()
    {
        $sql = "CREATE TABLE IF NOT EXISTS `yx_excel` (
                    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                    `excel` longtext COMMENT 'excel数据',
                    `effective_time` varchar(255) DEFAULT NULL COMMENT '有效期',
                    `secret_key` varchar(255) DEFAULT NULL,
                    `header1` varchar(255) DEFAULT NULL,
                    `header2` varchar(255) DEFAULT NULL,
                    `page` int(11) DEFAULT NULL COMMENT '页数',
                    `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',
                    PRIMARY KEY (`id`)
                ) ENGINE=InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='excel导出表';";
        db_query($sql);

        if (!db_fieldexists('yx_excel', 'open_num')) {
            $sql = "ALTER TABLE `yx_excel` ADD COLUMN `open_num` int(4) DEFAULT 0 comment '打开次数';";
            db_query($sql);
        }

        if (!db_fieldexists('yx_excel', 'software')) {
            $sql = "ALTER TABLE `yx_excel` ADD COLUMN `software` varchar(10) NOT NULL COMMENT '活动编号';";
            db_query($sql);
        }

    }

// function createposter($src,$file){
//  global $_G;
//  //load_func('file');
//  $url = explode(',',$src);
//  $filename = date('YmdHis').'_'.rand(1000000000,9999999999).'_'.rand(1000,9999).'.png';
//  $wr = file_write('/images/water_live2/'.$filename, base64_decode($url[1]));
//  $savepath =  'images/water_live2/'.$filename;
//  return $savepath;
// }
//手机版上传图片
    public static function YxUploadImg($params)
    {
        $file = $_FILES;
        if (empty($file)) {
            return ['error' => 1, 'msg' => '请上传图片'];
        }
        $upload_key = 'file';
        $key_arr = array_keys($file);
        if (!empty($key_arr)) {
            $upload_key = $key_arr[0];
        }
        $uplad_tmp_name = $file[$upload_key]['tmp_name'];
        $new_name = $upload_key . '-' . date('Ymdhis') . rand(10000, 99999) . '.jpg';
        //移动临时文件到指定图片目录，然后上传远程后删除
        $img_dir = ATTACHMENT_ROOT . 'workqr/' . MODULE_NAME . '/';
        if (!is_dir($img_dir)) {
            mkdirs($img_dir, 0700);
        }
        $move_res = move_uploaded_file($uplad_tmp_name, $img_dir . $new_name);
        if (!$move_res) {
            return ['error' => 1, 'msg' => '写入图片失败，请重试'];
        } else {
            $remotestatus = file_remote_upload($img_dir . $new_name); //上传图片到远程
            if ($remotestatus['code'] != 1) {
                yxlog('员工上传二维码失败：' . $remotestatus['msg'], '上传OSS失败');
                return ['error' => 1, 'msg' => '上传图片失败，请重试'];
            } else {
                $img = $remotestatus['data']['url'];  // 远程图片的访问URL
                return ['error' => 200, 'msg' => '上传图片成功', 'remotepath' => $img];
            }
        }
    }
}
